<template>
  <div class="favorites-container">
    <el-card class="favorites-card">
      <template #header>
        <h2 class="favorites-title">我的收藏</h2>
      </template>
      
      <div v-if="loading" class="loading-state">
        <el-skeleton :rows="3" animated />
      </div>
      
      <div v-else-if="favorites.length === 0" class="empty-state">
        <el-empty description="暂无收藏商品" />
      </div>
      
      <div v-else class="favorites-grid">
        <el-card
          v-for="product in favorites"
          :key="product.id"
          class="product-card"
          @click="handleProductClick(product)"
        >
          <el-image
            :src="getProductImage(product.coverList)"
            class="product-image"
            fit="cover"
            :preview-src-list="getProductImages(product.coverList)"
          />
          <div class="product-info">
            <h3 class="product-name">{{ product.name }}</h3>
                         <div class="product-owner">
               <span class="owner-label">卖家：</span>
               <span class="owner-name">{{ maskUserName(userInfoMap.get(product.userId)?.userName || userInfoMap.get(product.userId)?.userAccount || '未知用户') }}</span>
             </div>
            <div class="product-price">
              <span class="current-price">¥{{ product.price }}</span>
            </div>
            <div class="product-meta">
              <div class="product-tags">
                <el-tag v-if="product.isBargain" type="success" size="small">可砍价</el-tag>
                <el-tag type="info" size="small">{{ getOldLevelText(product.oldLevel) }}</el-tag>
              </div>
              <span class="time">{{ formatTime(product.createTime) }}</span>
            </div>
          </div>
          <div class="product-actions">
            <el-button
              size="small"
              type="danger"
              @click.stop="handleRemoveFavorite(product)"
            >
              取消收藏
            </el-button>
          </div>
        </el-card>
      </div>
      
      <div v-if="total > 0" class="pagination-wrapper">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[12, 24, 48, 96]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, getCurrentInstance } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import dayjs from 'dayjs'
import { useProductStore } from '@/stores/product'
import { useUserStore } from '@/stores/user'
import request from '@/utils/request'
import { getOldLevelText, maskUserName } from '@/utils/product'

const router = useRouter()
const productStore = useProductStore()
const userStore = useUserStore()

const favorites = ref<any[]>([])
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(12)
const total = ref(0)
const userInfoMap = ref<Map<number, any>>(new Map())

const formatTime = (time: string) => {
  return dayjs(time).format('MM-DD HH:mm')
}

const getProductImage = (coverList: string) => {
  try {
    if (!coverList) return '/placeholder.svg'
    return coverList  ? coverList : '/placeholder.svg'
  } catch {
    return '/placeholder.svg'
  }
}

const getProductImages = (coverList: string) => {
  try {
    if (!coverList) return ['/placeholder.svg']
    const images = JSON.parse(coverList)
    return images && images.length > 0 ? images : ['/placeholder.svg']
  } catch {
    return ['/placeholder.svg']
  }
}

// 获取用户信息
const fetchUserInfo = async (userId: number) => {
  if (userInfoMap.value.has(userId)) {
    return userInfoMap.value.get(userId)
  }
  
  try {
    const userInfo = await userStore.getUserById(userId)
    if (userInfo) {
      userInfoMap.value.set(userId, userInfo)
    }
    return userInfo
  } catch (error) {
    console.error('获取用户信息失败:', error)
    return null
  }
}

const loadFavorites = async () => {
  try {
    loading.value = true
    
    // 检查用户是否已登录
    if (!userStore.user || !userStore.user.username) {
      ElMessage.error('请先登录')
      router.push('/login')
      return
    }
    
    const result = await productStore.getUserCollect({
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      userName: userStore.user.username,
      type: 1 // 收藏类型
    })
    
    favorites.value = result.list
    total.value = result.total
    
    // 为每个商品获取用户信息
    for (const product of favorites.value) {
      if (product.userId) {
        await fetchUserInfo(product.userId)
      }
    }
  } catch (error: any) {
    console.error('获取收藏列表失败:', error)
    if (error.message && error.message.includes('用户没有收藏')) {
      favorites.value = []
      total.value = 0
    } else {
      ElMessage.error('获取收藏列表失败')
    }
  } finally {
    loading.value = false
  }
}

const handleProductClick = (product: any) => {
  router.push(`/product/${product.id}`)
}

const handleRemoveFavorite = async (product: any) => {
  try {
    // 检查用户是否已登录
    if (!userStore.user || !userStore.user.username) {
      ElMessage.error('请先登录')
      router.push('/login')
      return
    }
    
    await ElMessageBox.confirm(
      '确定要取消收藏这个商品吗？',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
  
    
    // 调用后端删除收藏API
    const deleteParams = {
      userName: userStore.user.username,
      type: 1, // 收藏类型
      productId: product.id
    }
    
    console.log('取消收藏 - 传递给后端的数据:', deleteParams)
    
    const response = await request.delete('/interaction/delete', {
      params: deleteParams
    })
   
    
    ElMessage.success('取消收藏成功')
    loadFavorites()
    
    // 通知父组件刷新统计数据
    const parentComponent = getCurrentInstance()?.parent
    if (parentComponent && parentComponent.exposed?.refreshStats) {
      parentComponent.exposed.refreshStats()
    }
  } catch (error: any) {
    if (error !== 'cancel') {
      ElMessage.error('取消收藏失败')
    }
  }
}

const handleSizeChange = (size: number) => {
  pageSize.value = size
  currentPage.value = 1
  loadFavorites()
}

const handleCurrentChange = (page: number) => {
  currentPage.value = page
  loadFavorites()
}

onMounted(() => {
  loadFavorites()
})
</script>

<style scoped lang="scss">
.favorites-container {
  padding: 30px;
  background: #f5f7fa;
  min-height: 100vh;
}

.favorites-card {
  max-width: 1200px;
  margin: 0 auto;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  
  :deep(.el-card__header) {
    background: linear-gradient(135deg, #ff6b35 0%, #f7931e 100%);
    color: white;
    border-radius: 12px 12px 0 0;
  }
}

.favorites-title {
  text-align: center;
  margin: 0;
  color: white;
  font-size: 24px;
  font-weight: 600;
}

.loading-state {
  padding: 40px;
}

.empty-state {
  text-align: center;
  padding: 60px 0;
}

.favorites-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 20px;
  margin-bottom: 30px;
}

.product-card {
  cursor: pointer;
  transition: transform 0.2s, box-shadow 0.2s;
  border-radius: 8px;
  overflow: hidden;
  
  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
  }
}

.product-image {
  width: 100%;
  height: 200px;
  border-radius: 8px 8px 0 0;
}

.product-info {
  padding: 16px;
}

.product-name {
  font-size: 16px;
  margin: 0 0 8px;
  color: #2c3e50;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  font-weight: 600;
}

.product-owner {
  margin-bottom: 8px;
  font-size: 14px;
  color: #666;
}

.owner-label {
  color: #999;
}

.owner-name {
  color: #409eff;
  font-weight: 500;
}

.product-price {
  margin-bottom: 12px;
}

.current-price {
  font-size: 20px;
  color: #ff6b35;
  font-weight: bold;
}

.product-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.product-tags {
  display: flex;
  gap: 8px;
}

.time {
  font-size: 12px;
  color: #7f8c8d;
}

.product-actions {
  padding: 0 16px 16px;
  text-align: center;
}

.pagination-wrapper {
  text-align: center;
  margin-top: 30px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .favorites-container {
    padding: 15px;
  }
  
  .favorites-grid {
    grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
    gap: 15px;
  }
  
  .favorites-title {
    font-size: 20px;
  }
}
</style> 